from tcp_server_u8_thread import TcpReceiverThread

import sys
import socket
import threading
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QLabel, QWidget
from curve_plotter import CurvePlotter

import struct

from pyqtgraph.Qt import QtCore
import pyqtgraph as pg
import numpy as np
from dspx2 import DSPx2


pkg_len = 326

CH_NUM_PER_CHIP = 8
CHIP_NUM = 1
CH_NUM = CH_NUM_PER_CHIP*CHIP_NUM
SN_PKG = 10 # sample number per package
int_size = 4
real_value_factor = 0.1341
int_size_chs = int_size*CH_NUM

HEADER_LEN = 4
tail_LEN = 2
# payload_len = 270
payload_len = 320


app = pg.mkQApp("Plotting Example")
#mw = QtWidgets.QMainWindow()
#mw.resize(800,800)

win = pg.GraphicsLayoutWidget(show=True, title="Basic plotting examples")
# pg.setConfigOptions(antialias=True)
pw = win.addPlot(title="Sig")


pw.setLabel('bottom', 'Time', 's')

cp = CurvePlotter(1, 2, 3, name="Alice", age=30,pw = pw, fs=500)

dsp2 = DSPx2(500, 8)


def deal_payload(data):

    # print(data[0:12])
    arr_int =  np.zeros((SN_PKG,CH_NUM),dtype = np.int32) # one sample point,with 24 channels 

    for samp in range(SN_PKG):
        offset_samp = samp*CH_NUM*int_size
        for ch in range(CH_NUM):
            star_ind = ch*int_size+offset_samp
            int_bytes = data[star_ind:star_ind+int_size]
            # print(len(int_bytes))
            v = struct.unpack('<i', int_bytes)[0] # small_endian
            arr_int[samp,ch] = v*real_value_factor


    # arr_int = dsp2.filter(arr_int)
    arr_int = dsp2.filter_dummy(arr_int)
    cp.new_data(arr_int)


tcp_thread = TcpReceiverThread('192.168.43.9', 6002)
# tcp_thread = TcpReceiverThread('192.168.0.24', 6002)
tcp_thread.data_received_payload.connect(deal_payload)  # 将接收到的数据传递给 UI 更新
tcp_thread.start()

pg.exec()
tcp_thread.stop()

